import React, { useEffect, useState } from 'react'
import { useLocation,useNavigate } from 'react-router-dom'
import EditorPlus from '../../../components/EditorPlus'
import { Button, Select, Row, message } from 'antd';
import request from '../../../utils/request'
import './index.less'

export default function Write() {
  const location = useLocation()
  const { Option } = Select;
  const navigate = useNavigate()

  //文章信息
  //文章标题
  const [title, setTitle] = useState('')
  //分类数组
  const [categoryList, setCagoryList] = useState([])
  //选择的分类id
  const [cid, setCid] = useState('')
  //文章纯文本
  const [contentText, setContentText] = useState('')
  //文章id
  const [id,setId] = useState(0)

  //获取文章
  const getArticle = async () => {
    const { search } = location
    if (!search) return
    let ID = search.slice(4)
    setId(ID)
    const res = await request.get(`/v1/article/info/${ID}`)
    console.log(res);
    if (res.status === 200) {
      const { title, content, cid } = res.data
      setTitle(title)
      localStorage.setItem(ID,content)
      setCid(cid)
    }
  }

  //获取分类列表
  const getCategory = async () => {
    const res = await request.get('/v1/category')
    console.log(res);
    if (res.status === 200) {
      //动态添加分类选项
      let options = res.data.map((option) => {
        return <Option key={option.id} value={option.id}>{option.name}</Option>
      })
      setCagoryList(options)
    }
  }


  //选择分类
  function handleChange(value) {
    setCid(value)
  }

  //添加文章或修改
  const addArtcle = async () => {
    let text = contentText.replace(/\s+/g, ' ');
    const desc = text.substr(0, 200)
    console.log(desc);
    if (cid === 0) return message.error('请选择分类')
    if(id === 0){
      const data = await request.post('/v1/article/add', {
        title,
        cid,
        desc,
        content:localStorage.getItem('newArticle'),
        img: ''
      })
      console.log(data);
      if(data.status === 200){
        message.success('发布成功')
        navigate('/file/fileList')
      }
      else{
        message.error(data.message)
      }
    }
    else{
      const data = await request.put(`/v1/article/${id}`, {
        title,
        cid,
        desc,
        content:localStorage.getItem('newArticle'),
        img: ''
      })
      console.log(data);
      if(data.status === 200){
        message.success('修改成功')
        navigate('/file/fileList')
      }
      else{
        message.error(data.message)
      }
    }

  };

  useEffect(() => {
    getCategory()
    getArticle()
  }, [])

  return (
    <>
      <input type="text" className='title' placeholder='文章标题' value={title || ''} onChange={(e) => setTitle(e.target.value)} />
      <EditorPlus id={id}   setContentText={setContentText} />
      <Row gutter='20' justify="center">
        <Select value={cid===''?'请选择分类':cid} className='select' onChange={handleChange}>
          {categoryList}
        </Select>
        <Button type="primary" onClick={addArtcle} className='submit'>{id === 0?'发布文章':'修改文章'}</Button>
      </Row>
    </>
  )
}
